package com.cd2cd.code_app.dispatcher;

import com.alibaba.fastjson.JSONObject;

import com.cd2cd.code_app.App;
import com.cd2cd.code_app.util.Constants;
import com.cd2cd.code_app.util.DBUtil;
import com.cd2cd.code_app.util.FileUtil;
import javafx.application.Platform;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

public class DispatcherHandle {

    public String dispatcher(String params) throws Exception {

        JSONObject resJson = new JSONObject();
        resJson.put("code", 0);
        try {

            System.out.println("params=" + params);

            ActionType actionType = new ActionType(params);
            System.out.println(actionType.type);

            String resStr = null;
            switch (actionType.type) {
                case start:
                    resStr = start();
                    break;

                case openTab:
                    resStr = openTab(actionType.params);
                    break;

                case readSetting:
                case saveSetting:
                    String res = operSetting(actionType.params);
                    System.out.println(res);
                    resStr = res;
                    break;

                case openSetting:
                    String url = App.class.getResource("/html/config.html").toExternalForm();
                    App.addTab(url, "系统设置");
                    break;

                case openInBrowser:
                    openInBrowser();
                    break;
            }

            System.out.println("**********" + params);

            if (StringUtils.isNotBlank(resStr)) {
                System.out.println(resStr);
                return resStr;
            } else {

                return resJson.toJSONString(); // 没有设置信息
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resJson.toJSONString(); // 没有设置信息
    }

    /**
     * 打开标签
     * @param params
     * @return
     */
    private String openTab(String params) {

        Platform.runLater(() -> {
            JSONObject obj = JSONObject.parseObject(params);
            String url = obj.getString("url");
            App.addTab(url, null);
        });
        return "{code:0}";
    }

    /**
     * 读取配置信息 - db
     * @return
     */
    private String operSetting(String params) throws Exception {
        JSONObject jsonObj = JSONObject.parseObject(params);
        String oper = jsonObj.getString("oper");

        if("read".equals(oper)) {
            if(FileUtil.hasSetting()) {
                JSONObject json = FileUtil.readCustomerApplicationPro();
                return json.toJSONString();
            } else {

                FileUtil.copyCodeMain();
                JSONObject json = FileUtil.readJarApplicationPro();

                JSONObject resJson = new JSONObject();
                resJson.put("database", json.getString("database"));
                resJson.put("code", 1001);
                return resJson.toJSONString(); // 没有设置信息
            }
        } else if("save".equals(oper)) {


            // 测试是否可连接
            String host = jsonObj.getString("host");
            String username = jsonObj.getString("username");
            int port = jsonObj.getInteger("port");
            String password = jsonObj.getString("password");
            String database = jsonObj.getString("database");

            JSONObject resJson = new JSONObject();
            resJson.put("code", 0);

            // 测试数据名是否已存在
            try {
                List<Map<String, Object>> list = DBUtil.exeQuerySql("select 1", host, port, username, password, "");
            } catch (Exception e) {
                resJson.put("code", -1);
                resJson.put("msg", e.getMessage());
                return resJson.toJSONString();
            }

            // 测试【账号】是否有创建数据库权限

            // 判断数据库是否存在， 数据库不存并且当前账号无创断数据库权限，提示错误。

            // 数据库存在时，判断是否有建表权限。

            // +++++++ 保存数据
            FileUtil.saveCustomerApplicationPro(host, username, password, port, database);

            return resJson.toJSONString();
        }
        return "{\"code\":0}";
    }

    private String start() throws Exception {

        JSONObject resJson = new JSONObject();

        /**
         * 检测服务启动情况: 2001启动中；3001启动失败；2002运行中；3002未配置文件
         */

        // 是否配置服务文件
        if( ! FileUtil.hasSetting()) {
            resJson.put("code", 3002);
            return resJson.toJSONString();
        }

        // 初始化数据库：1、创建数据库；2、初始化数据表；
        // 数据库是否创建成功；3003; 3004：初始数据库表失败；
        JSONObject json = FileUtil.readCustomerApplicationPro();
        String dbName = json.getString("database");
        String host = json.getString("host");
        String username = json.getString("username");
        String password = json.getString("password");
        int port = json.getInteger("port");

        boolean hasDb = DBUtil.hasDatabase(dbName, host, port, username, password);
        System.out.println("hasDb=" + hasDb);

        if( ! hasDb) {

            boolean isSuccess = DBUtil.createDatabase(dbName, host, port, username, password);
            if( ! isSuccess) {
                resJson.put("code", 3003); // 失败-数户库用户没有创建数据库权限
                return resJson.toJSONString();
            }

            // 初始数据
            DBUtil.initDatabaseData(dbName, host, port, username, password);

        } else {

            // 更新数据库脚本
            DBUtil.updateDbSql(dbName, host, port, username, password);
        }

        if(App.WEB_SERVICE != null) {
            if(App.WEB_SERVICE.isAlive()) {
                resJson.put("code", 2002); // 运行中
            } else {
                resJson.put("code", 3001); // 启动失败
            }
            return resJson.toJSONString();
        }

        // 判断 code_main.jar 是否存在；不存在cp 到 code-manager/下；
        FileUtil.copyCodeMain();

        new Thread(() -> {

            // 启动程序


            // 前面页面显示启动日志


            // jar path
            System.out.println("******-start-2");
            String jarPath = FileUtil.getPath()+FileUtil.service_path;
            String proPath = FileUtil.getPath()+FileUtil.setting_path;
            System.out.println("jarPath=" + jarPath);
            String command = "java -jar "+jarPath + " --spring.config.location=" + proPath;
            try {

                Process process = Runtime.getRuntime().exec(command);
                App.WEB_SERVICE = process;

                InputStream input = process.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(input));

                String line = br.readLine();
                while( line != null ) {

                    System.out.println(line);
                    line = br.readLine();

                    if(line != null && line.indexOf("Tomcat started") > -1) {
                        Platform.runLater(() -> {
                            App.addTab(Constants.PROJECT_URL, "项目管理");
                        });
                    }
                }

                System.out.println("----- error 启动错误 ......");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();


        resJson.put("code", 2001);// 启动中
        return resJson.toJSONString();
    }

    public static void openInBrowser() {
        if (java.awt.Desktop.isDesktopSupported()) {
            try {
                java.net.URI uri = java.net.URI.create(Constants.PROJECT_URL);
                java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
                    dp.browse(uri);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String jarPath = "/Users/lwl/Documents/source-code/java-code/code_2_code/cd2cd/code_main/target/code_main.jar";
        System.out.println("jarPath=" + jarPath);
        String command = "java -jar " + jarPath;
//        command = "java -jar /Users/lwl/Documents/source-code/java-code/code2code/target/code2code-1.0-SNAPSHOT.jar ";//+jarPath + " ";
        try {
            Process process = Runtime.getRuntime().exec(command);
            InputStream input = process.getErrorStream();
            String str = IOUtils.toString(input, "utf-8");
            System.out.println("error="+str);
            InputStream runInput = process.getInputStream();

            str = IOUtils.toString(runInput, "utf-8");
            System.out.println("input="+str);

            process.waitFor();

        } catch (Exception e) {
            System.out.println("e="+e.getMessage());
        }
    }
}
